package controller

import (
	"GoAdmin/models"
	"GoAdmin/utils"
	"bytes"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/astaxie/beego"
	"github.com/beego/beego/v2/core/config"
	"github.com/tealeg/xlsx"
	"io/ioutil"
	"log"
	"os"
	"reflect"
	"time"
)

var userMap map[string]map[string]string = map[string]map[string]string{
	"id_type":          map[string]string{"1": "身份证", "2": "护照", "3": "军官证", "4": "其他"},
	"sex":              map[string]string{"1": "男", "2": "女"},
	"operation_status": map[string]string{"0": "初领", "1": "增领", "9": "其他", "11": "货运运营初领", "12": "货运运营增领"},
	"charge_mode":      map[string]string{"1": "一次性缴费", "2": "计时收费", "9": "其他"},
	"status":           map[string]string{"0": "已报名", "1": "培训部分一", "2": "培训部分二", "3": "培训部分三", "4": "培训部分四", "5": "停止练车", "6": "已结业"},
}

func SetHeader(sheet_header *xlsx.Sheet, showstr map[string]string, str []string) {
	row = sheet_header.AddRow()
	for _, v := range str {
		cell = row.AddCell()
		cell.Value = showstr[(string)(v)]
	}
}

func SetContents(sheet *xlsx.Sheet, v interface{}, currShowStr []string, strType string) {
	switch strType {
	case "1":
		if has, ok := v.(*models.DownStudent); ok {
			fields := reflect.TypeOf(has)
			getValue := reflect.ValueOf(has)
			row = sheet.AddRow()
			for _, vs := range currShowStr {
				for i := 0; i < fields.Elem().NumField(); i++ {
					if vs == fmt.Sprint(fields.Elem().Field(i).Tag.Get("json")) {
						cell = row.AddCell()
						text := fmt.Sprint(getValue.Elem().Field(i).Interface())
						if userMap[vs] != nil {
							cell.Value = userMap[vs][text]
						} else {
							cell.Value = text
						}
					}
				}
			}
		} else {
		}

	default:
	}
}

func ExcelDir() (export_dir string, err error) {
	basedir := beego.AppConfig.String("exprotexcel")
	dir := time.Now().Format("20060102")
	other_dir := time.Now().AddDate(0, 0, -1).Format("20060102")
	export_dir = basedir + dir
	fmt.Println("获取根目录")
	fmt.Println(basedir)
	fmt.Println(export_dir)
	exist, err := PathExists(export_dir)
	if err != nil {
		fmt.Printf("获取目录失败![%v]\n", err)
		return "", err
	}

	if exist {
		fmt.Printf("存在目录![%v]\n", export_dir)
		return export_dir, err
	} else {
		fmt.Printf("不存在目录![%v]\n", export_dir)
		err := os.RemoveAll(basedir + other_dir)
		if err != nil {
			return "", err
		}
		fmt.Printf("删除成功![%v]\n", other_dir)
		// 创建文件夹
		err = os.Mkdir(export_dir, os.ModePerm)
		if err != nil {
			fmt.Printf("创建失败![%v]\n", export_dir)
		} else {
			fmt.Printf("创建成功!\n")
		}
		return export_dir, err
	}
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		fmt.Println("e", err)
		return false, nil
	}
	return false, err
}

func UploadOss(down_dir string) string {
	var (
		data       []byte
		err        error
		client     *oss.Client
		bucket     *oss.Bucket
		uploadPath string
		exportDir  string
	)
	basedir := beego.AppConfig.String("exprotexcel")
	exportDir = basedir + down_dir
	if data, err = ioutil.ReadFile(exportDir); err != nil {
		fmt.Println(err.Error())
		//c.String(http.StatusBadRequest, fmt.Sprintf("get file err : %s", err.Error()))
		return ""
	}
	// 上传到oss
	conf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		log.Println("配置文件载入错误")
	}

	ossSection, err := conf.GetSection("oss")
	if err != nil {
		log.Println("配置文件载入错误-数据库-section载入失败")
	}
	if client, err = oss.New(ossSection["oss_endpoint"], ossSection["oss_access_id"], ossSection["oss_access_key"]); err != nil {
		return "0"
	}
	if bucket, err = client.Bucket(ossSection["oss_bucket"]); err != nil {
		return "0"
	}

	ids := fmt.Sprint(time.Now().UnixNano()) + utils.RandomCode(6) + ".xlsx"
	uploadPath = "excel"
	// 构造文件名
	fileName := fmt.Sprintf("%s/%s/%s", uploadPath, time.Now().Format("20060102"), ids)
	//fmt.Println(data, 222)
	if err = bucket.PutObject(fileName, bytes.NewReader(data)); err != nil {
		fmt.Println(err.Error())
		//c.String(http.StatusBadRequest, fmt.Sprintf("get file err : %s", err.Error()))
		return ""
	}
	return ossSection["oss_website"] + fileName
}
